//
//  MainMapViewController.m
//  Hive
//
//  Created by 惠俊贝 on 15/9/2.
//  Copyright (c) 2015年 ZM. All rights reserved.
//

#import "MainMapViewController.h"
#import "ABNetworkUtil.h"
#import "UserDefaultUtil.h"
#import "EqpInfo.h"
#import "CustomAnnotationView.h"
#import "AppDelegate.h"
#import "LeftSlideViewController.h"
#import "AlarmViewController.h"
#import "CarsViewController.h"


#define kCalloutViewMargin          -8

@interface MainMapViewController () {
    NSInteger eqpSelectedIndex;         // 当前设备索引号
    
    NSArray *eqpInfoArr;
    NSMutableArray *annotationMArr;
    
    UIButton *mapTypeButton;
    UIButton *showTrafficButton;
    UIButton *carOrHumanButton;

}

@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;

@end

@implementation MainMapViewController
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

}
- (void)viewDidLoad {
    self.title = @"Hive";
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    menuButton.hidden = NO;
    alarmButton.hidden = NO;
    refreshButton.hidden = NO;
    carInfoButton.hidden = NO;

    mapTypeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    mapTypeButton.frame = CGRectMake(SCREEN_WIDTH-40-10, NAVIGATTION_HEIGHT+STATUS_BAR_HEIGHT+10, 40, 40);
    [mapTypeButton setImage:[UIImage imageNamed:@"nav_more2_normal"] forState:UIControlStateNormal];
    [mapTypeButton addTarget:self action:@selector(mapTypeButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:mapTypeButton];
    

    
    showTrafficButton = [UIButton buttonWithType:UIButtonTypeCustom];
    showTrafficButton.frame = CGRectMake(SCREEN_WIDTH-40-10, CGRectGetMaxY(mapTypeButton.frame)+10, 40, 40);
    [showTrafficButton setImage:[UIImage imageNamed:@"nav_map_load_normal"] forState:UIControlStateNormal];
    [showTrafficButton setImage:[UIImage imageNamed:@"nav_map_load_pressed"] forState:UIControlStateSelected];
    [showTrafficButton addTarget:self action:@selector(showTrafficButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:showTrafficButton];
    
    
    carOrHumanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    carOrHumanButton.frame = CGRectMake(SCREEN_WIDTH-40-10,  CGRectGetMaxY(showTrafficButton.frame)+10, 40, 40);
    [carOrHumanButton setImage:[UIImage imageNamed:@"location3_normal"] forState:UIControlStateNormal];
    [carOrHumanButton setImage:[UIImage imageNamed:@"location2_normal"] forState:UIControlStateSelected];
    [carOrHumanButton addTarget:self action:@selector(carOrHunmanButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:carOrHumanButton];
    
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, (SCREEN_HEIGHT-150)/2, 40, 150);
    [leftButton setImage:[UIImage imageNamed:@"map_btnleft"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(preEqpPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setImage:[UIImage imageNamed:@"map_btnright"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(nextEqpPress:) forControlEvents:UIControlEventTouchUpInside];
    rightButton.frame = CGRectMake(SCREEN_WIDTH-40, (SCREEN_HEIGHT-150)/2, 40, 150);
    [self.view addSubview:rightButton];
    
    self.mapView.visibleMapRect = MAMapRectMake(220880104, 101476980, 272496, 466656);
    self.mapView.zoomLevel = 13;
    
    [self refreshEqpInfo];

    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshEqpInfo {
    NSString *token = [UserDefaultUtil getToken];
    [[[ABNetworkUtil alloc] init]
     getSelfUserEqpInfoWithToken:token
     success:^(id response) {
         NSDictionary *dic = (NSDictionary *)response;
         if ([[dic objectForKey:@"Result"] integerValue] == 0) {
             //成功
             NSArray *arr = [[dic objectForKey:@"DataList"]
                             objectForKey:@"Response_EqpInfo"];
             eqpInfoArr = [EqpInfo createEqpInfosWithDicArray:arr];
             [self addAllEqpAnnotationWithEqpInfoArray:eqpInfoArr];
         }
         
     } fail:^(NSError *error) {
         NSLog(@"%@",error.localizedDescription);
     }];
    
}

#pragma mark - event
- (void)mapTypeButtonPress:(id)sender {

    switch (self.mapView.mapType) {
        case MAMapTypeStandard: {
            self.mapView.mapType = MAMapTypeSatellite;
            break;
        }
        case MAMapTypeSatellite: {
            self.mapView.mapType = MAMapTypeStandard;
            break;
        }
        default: {
            break;
        }
    }
}

- (void)carOrHunmanButtonPress:(id)sender {
    carOrHumanButton.selected = !carOrHumanButton.selected;
    if (carOrHumanButton.selected) {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
    else {
        [self locateEqpInfo];
    }
}

- (void)showTrafficButtonPress:(id)sender {
    
    self.mapView.showTraffic = !self.mapView.showTraffic;
    [showTrafficButton setSelected:self.mapView.showTraffic];
}

- (void)menuButtonPress:(id)sender {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UINavigationController *rootNavVC = appDelegate.navigationController;
    for (id vc in rootNavVC.viewControllers) {
        if ([vc isKindOfClass:[LeftSlideViewController class]]) {
            LeftSlideViewController *LeftSlideVC = (LeftSlideViewController *)vc;
            if (LeftSlideVC.closed)
            {
                [LeftSlideVC openLeftView];
            }
            else
            {
                [LeftSlideVC closeLeftView];
            }
        }
    }

    
}

- (void)alarmButtonPress:(id)sender {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UINavigationController *rootNavVC = appDelegate.navigationController;
    AlarmViewController *toController = [[AlarmViewController alloc] initWithNibName:@"AlarmViewController" bundle:nil];
    [rootNavVC pushViewController:toController animated:YES];
}


- (void)refreshButtonPress:(id)sender {
    [self.mapView removeAnnotations:annotationMArr];
    [self refreshEqpInfo];
}

- (void)carInfoButtonPress:(id)sender {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UINavigationController *rootNavVC = appDelegate.navigationController;
    CarsViewController *toController = [[CarsViewController alloc] initWithNibName:@"CarsViewController" bundle:nil];
    [rootNavVC pushViewController:toController animated:YES];
}

- (void)preEqpPress:(id)sender {
    if (eqpSelectedIndex == 0) {
        eqpSelectedIndex = [eqpInfoArr count]-1;
    }
    else {
        eqpSelectedIndex --;
    }
    [self locateEqpInfo];
}

- (void)nextEqpPress:(id)sender {
    if (eqpSelectedIndex == [eqpInfoArr count]-1) {
        eqpSelectedIndex = 0;
    }
    else {
        eqpSelectedIndex ++;
    }
    [self locateEqpInfo];
}

- (void)locateEqpInfo {
    MAPointAnnotation *pointAnnotition = [annotationMArr objectAtIndex:eqpSelectedIndex];
    if (pointAnnotition) {
        [self.mapView setCenterCoordinate:pointAnnotition.coordinate animated:YES];
    }
    
}

#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        
        EqpInfo *eqp;
        MAPointAnnotation *a = (MAPointAnnotation *)annotation;
        for (EqpInfo *e in eqpInfoArr) {
            if ([e.DeviceID isEqualToString:a.title]) {
                eqp = e;
            }
        }
        
        
        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        
        CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        if ([eqp.IsOnline boolValue]) {
            
            annotationView.portrait = [UIImage imageNamed:@"car_online1"];
        }
        else {
            annotationView.portrait = [UIImage imageNamed:@"car_static1"];
        }
        annotationView.eqpInfo = eqp;
        return annotationView;
    }
    
    return nil;
}



- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation && self.userLocationAnnotationView != nil)
    {
        [UIView animateWithDuration:0.1 animations:^{
            
            double degree = userLocation.heading.trueHeading;
            self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );
            
        }];
    }
    
}

- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MAAnnotationView *view = [views firstObject];
    
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
        pre.fillColor = [UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.3];
        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
        pre.image = [UIImage imageNamed:@"userPosition"];
        pre.lineWidth = 3;
        //        pre.lineDashPattern = @[@6, @3];
        
        [self.mapView updateUserLocationRepresentation:pre];
        
        view.calloutOffset = CGPointMake(0, 0);
        view.canShowCallout = NO;
        self.userLocationAnnotationView = view;
    }  
}

#pragma mark - Action Handle

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    /* Adjust the map center in order to show the callout view completely. */
    if ([view isKindOfClass:[CustomAnnotationView class]]) {
        CustomAnnotationView *cusView = (CustomAnnotationView *)view;
        CGRect frame = [cusView convertRect:cusView.calloutView.frame toView:self.mapView];
        
        frame = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin));
        
        if (!CGRectContainsRect(self.mapView.frame, frame))
        {
            /* Calculate the offset to make the callout view show up. */
            CGSize offset = [self offsetToContainRect:frame inRect:self.mapView.frame];
            
            CGPoint theCenter = self.mapView.center;
            theCenter = CGPointMake(theCenter.x - offset.width, theCenter.y - offset.height);
            
            CLLocationCoordinate2D coordinate = [self.mapView convertPoint:theCenter toCoordinateFromView:self.mapView];
            
            [self.mapView setCenterCoordinate:coordinate animated:YES];
        }
        
    }
}

#pragma mark - Utility

- (void)addAllEqpAnnotationWithEqpInfoArray:(NSArray *)arr {
    annotationMArr = [[NSMutableArray alloc] init];
    for (EqpInfo *eqp in arr) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(eqp.GDLat, eqp.GDLng);
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = coordinate;
        annotation.title = eqp.DeviceID;
        [annotationMArr addObject:annotation];
        
    }
    [self.mapView addAnnotations:annotationMArr];
    MAPointAnnotation *first = [annotationMArr firstObject];
    [self.mapView setCenterCoordinate:first.coordinate];
}
//-(void)addAnnotationWithCooordinate:(CLLocationCoordinate2D)coordinate
//{
//    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
//    annotation.coordinate = coordinate;
//    annotation.title    = @"AutoNavi";
//    annotation.subtitle = @"CustomAnnotationView";
//    
//    [self.mapView addAnnotation:annotation];
//}

- (CGPoint)randomPoint
{
    CGPoint randomPoint = CGPointZero;
    
    randomPoint.x = arc4random() % (int)(CGRectGetWidth(self.view.bounds));
    randomPoint.y = arc4random() % (int)(CGRectGetHeight(self.view.bounds));
    
    return randomPoint;
}

- (CGSize)offsetToContainRect:(CGRect)innerRect inRect:(CGRect)outerRect
{
    CGFloat nudgeRight = fmaxf(0, CGRectGetMinX(outerRect) - (CGRectGetMinX(innerRect)));
    CGFloat nudgeLeft = fminf(0, CGRectGetMaxX(outerRect) - (CGRectGetMaxX(innerRect)));
    CGFloat nudgeTop = fmaxf(0, CGRectGetMinY(outerRect) - (CGRectGetMinY(innerRect)));
    CGFloat nudgeBottom = fminf(0, CGRectGetMaxY(outerRect) - (CGRectGetMaxY(innerRect)));
    return CGSizeMake(nudgeLeft ?: nudgeRight, nudgeTop ?: nudgeBottom);
}

@end
